<template>
  <div>
    <el-form class="tableSearch" size="mini">
      <el-form-item>
        <el-button type="primary" @click="$router.back(-1)">返回</el-button>
        <el-button v-if='setRole("修改")' v-show="showTab === 2" type="primary" @click="submitForm('formdata')">保存</el-button>
        <el-button v-if='setRole("审核")' v-show="formdata.inStatus == 1" type="primary" @click="handleVerify(0)">审核通过</el-button>
        <el-button v-if='setRole("审核")' v-show="formdata.inStatus == 1" type="primary" @click="handleVerify(3)">审核驳回</el-button>
      </el-form-item>
    </el-form>

    <el-form :model="formdata" ref="formdata" :rules="rules" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商：" prop="supplierName">
            <span>{{formdata.supplierName}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货状态：">
            <span>{{purchaseReceivingsStatusArr[formdata.inStatus]}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货日期：" prop="receiveDate">
            <span v-if="showTab === 1">{{formdata.receiveDate}}</span>
            <el-date-picker v-if="showTab === 2" v-model="formdata.receiveDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择交货日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <span>{{formdata.orderDate}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据号：">
            <span>{{formdata.purchaseinCode}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="来源单号：">
            <span>{{formdata.deliveryCode}}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData">
      <el-table-column type="index" label="#" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      <el-table-column prop="barCode" label="商品条码" align="center" width="150"></el-table-column>
      <el-table-column prop="goodsName" label="商品" align="center" width="150"></el-table-column>
      <el-table-column prop="goodsBatchNumber" label="商品批次" align="center" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          <span v-if="showTab === 1">{{scope.row.goodsBatchNumber}}</span>
          <span v-if="showTab === 2&&scope.row.isBatch==1&&isShowtrue==0">{{scope.row.goodsBatchNumber}}</span>
          <input class="commonInput" v-if="showTab === 2&&scope.row.isBatch==1&&isShowtrue==1" v-model="scope.row.goodsBatchNumber" size="mini" type="text" style="width:100px" value="1" min="0" maxlength="8" oninput="value=value.replace(/[\W]/g,'')" onafterpaste="value=value.replace(/[\W]/g,'')">
        </template>
      </el-table-column>
      <el-table-column prop="dateInProduced" label="生产日期" align="center" width="200">
          <template slot-scope="scope">
            <el-date-picker  v-if="showTab === 2&&scope.row.isBatch==1&&isShowtrue=='1'"  size="small"  v-model="scope.row.dateInProduced" :picker-options="pickerOptions" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date"></el-date-picker>
            <span  v-if="showTab === 1">{{scope.row.dateInProduced}}</span>
            <span  v-if="showTab === 2&&scope.row.isBatch==1&&isShowtrue=='0'">{{scope.row.dateInProduced}}</span>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>
        </el-table-column>
      <el-table-column prop="warehouseName" label="仓库" align="center" width="200">
        <template slot-scope="scope">
          <span v-if="showTab === 1">{{scope.row.warehouseName}}</span>
          <el-input v-if="showTab === 2" v-model="scope.row.warehouseName" size="mini" disabled>
            <el-button class="buttonxz" type="primary" @click="openWarehouseDialog(scope.$index)" slot="append">选择</el-button>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
      <el-table-column prop="goodsSpec" label="规格型号" align="center">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
            <span>{{item.paramName}} :</span>
            <span>{{item.paramValue}} </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsNum" label="数量" align="center" width="150">
        <template slot-scope="scope">
          <span v-if="showTab === 1">{{scope.row.goodsNum}}</span>
          <input class="commonInput" v-if="showTab === 2" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="0" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
        </template>
      </el-table-column>
    </el-table>

    <el-form :model="formdata" label-width="120px" size="mini" style="margin-top:25px;">
      <el-row>
        <el-col :span="12">&nbsp;</el-col>
        <el-col :span="8">
          <el-form-item label="操作员：">
            <span>{{formdata.userName}}</span>
          </el-form-item>
          <el-form-item label="备注：">
            <span v-if="showTab === 1">{{formdata.remark}}</span>
            <el-input v-if="showTab === 2" v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 仓库选择弹出框 -->
    <el-dialog title="仓库选择" :visible.sync="warehouseClass.dialog" :closeOnClickModal='false' :closeOnPressEscape='false'>
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectWarehouse()">选择</el-button>
          <el-button @click="warehouseClass.dialog=false">取消</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="warehouseClass.tableData" highlight-current-row @current-change="warehouseClass.handleSingleSelect">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="repositoryName" label="仓库" align="center"></el-table-column>
        <el-table-column prop="repositoryAddress" label="地址" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="warehouseClass.pageData" :func="_getRepositoryListPage"></page-unit>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import SdInput from "@/components/SdInput";
import pageUnit from "components/Page";
import u from "@/util";
import s from "@/util/state";
import { TableHandle } from "@/util/class";
import {
  getRepertoryInBoundDetail,
  saveRepertoryInBound,
  auditRepertoryInBound,
  getRepositoryListPage
} from "@/api";
export default {
  components: { SdInput, pageUnit },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },//当前日期之后的不可选
      id: "",  // 主键id
      showTab: "",  // 查看/编辑
      purchaseReceivingsStatusArr: s.purchaseReceivingsStatusArr,
      cang_index: "",  // 选择仓库的商品在商品数组的位置
      tableData: [],  // 商品数组
      rules: {
        supplierName: [{ required: true}],
        receiveDate: [{ required: true, message: "请选择收货时间", trigger: "blur" }]
      },
      formdata: {
        supplierId: "",  // 供应商id
        supplierName: "",  // 供应商名称
        receiveDate: "",  // 收货日期
        orderDate: "",  // 单据日期
        purchaseinCode: "",  // 单据号
        remark: "",  // 备注
        purchaseAmount: 0,
        freight: 0,
        amount: 0,
        purchaseId: ''
      },
      isShowtrue: "",
      warehouseClass: new TableHandle()  // 仓库弹窗对象
    };
  },
  computed: mapState(["sub", "merchantId", "power", "path", "linkName", "mobile", "userId"]),
  created() {
    this.id = u.getQuery().id;  // 查看id
    this.showTab = Number(u.getQuery().showTab);  // 1 查看， 2 修改
  },
  mounted() {
    this.getDataById();
  },
  methods: {
    // 分配权限
    setRole (key) {
      return u.selectTitle(this.power, key)
    },

    // 处理审核状态
    handleVerify(state) {
      auditRepertoryInBound({
        id: this.id,
        inStatus: state
      }).then(res => {
        if(res.code == 200) {
          this.$message.success(res.msg)
          u.routerTo("/order-center/purchase-management/purchase-receiptMg")
        }
      })
    },

    // 查看详情
    getDataById() {
      getRepertoryInBoundDetail({
        id: this.id
      }).then(res => {
        this.formdata = res.data;
        this.tableData = res.data.goodsList;
        if(this.formdata.purchaseCode.substring(0,2)=='OB'){
           this.isShowtrue=0
        }else if(this.formdata.purchaseCode.substring(0,2)=='PU'){
           this.isShowtrue=1
        }
        this.formdata.supplierName = res.data.shopName;
        this.formdata.receiveDate = this.$set(this.formdata, 'receiveDate', u.foryear(res.data.orderDate))
        this.formdata.orderDate = u.foryear(res.data.createTime);
        this.formdata.purchaseinCode = res.data.inCode;
        this.formdata.deliveryCode = res.data.purchaseCode;
      });
    },

    // 获取仓库列表api
    _getRepositoryListPage(pageSize, pageNum) {
      getRepositoryListPage({
        keyword: "",
        pageSize: pageSize,
        pageNum: pageNum,
        shopId: this.merchantId,
        status: 0,
      }).then(res => {
        this.warehouseClass.tableData = res.data.list
        this.warehouseClass.pageData.totalItems = res.data.pageTotal
      });
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave()
        } else {
          return false
        }
      });
    },

    // 提交表单数据
    handleSave() {
      if (this.tableData.length == 0) {
        this.$message.error("商品不能为空")
        return false
      }
      if(this.tableData.some(i => i.goodsNum <= 0)) {
        this.$message.error("商品数量不能小于等于0")
        return false
      }
      this.tableData.forEach(i => {
        delete i.createTime;
        delete i.updateTime;
      });
      saveRepertoryInBound({
        id: this.id,
        shopId: this.merchantId,
        supplierId: this.formdata.supplierId,
        supplierName: this.formdata.supplierName,
        purchaseStatus: 1,
        orderDate: this.formdata.receiveDate,
        remark: this.formdata.remark,
        orderPurchaseId: this.formdata.purchaseId,
        creater: this.userId,
        inType: 1,
        goodsList: JSON.stringify(this.tableData),
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          u.routerTo("/order-center/purchase-management/purchase-receiptMg")
        }
      });
    },

    // 确定选择仓库
    handleSelectWarehouse() {
      if(this.warehouseClass.isSelect(1, this, '请先选择仓库！')) {
        let i = this.cang_index
        this.$set(this.tableData[i], "repositoryName", this.warehouseClass.singleSelectTable.repositoryName)
        this.tableData[i].warehouseName = this.warehouseClass.singleSelectTable.repositoryName
        this.tableData[i].warehouseId = this.warehouseClass.singleSelectTable.id
        this.warehouseClass.dialog = false
      }
    },

    // 选择仓库显示仓库弹窗
    openWarehouseDialog(index) {
      this._getRepositoryListPage(this.warehouseClass.pageData.pageSize, 1)
      this.cang_index = index
      this.warehouseClass.dialog = true
    },
  }
};
</script>

<style lang="less">
.el-input-group__append {
    background-color: #409eff;
    border-color: #409eff;
    color: #ffffff;
}

.el-dialog__header {
  background-color: #25a0e9;
  .el-dialog__title {
    color: #FFFFFF;
  }
  .el-dialog__close {
    color: #FFFFFF;
    &:hover{
      &:before {
        color: #FFFFFF;
      }
    }
  }
}
</style>
